package cn.lu.train.ui.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.widget.ImageView;

import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.signature.ObjectKey;

import java.io.File;

import butterknife.BindView;
import cn.lu.train.App;
import cn.lu.train.GlideApp;
import cn.lu.train.R;
import cn.lu.train.api.SplashApi;
import cn.lu.train.base.BaseActivity;
import cn.lu.train.mvp.presenter.splash.SplashPresenter;
import cn.lu.train.mvp.view.ISplashView;
import cn.lu.train.util.SharePreferenceUtils;

public class SplashActivity extends BaseActivity implements ISplashView{

    @BindView(R.id.iv_splash)
    ImageView mIvBackground;

    private Handler mHandler;
    private Runnable mRunnable;

    @Override
    public int getLayout() {
        return R.layout.activity_splash;
    }

    @Override
    protected void onCreated() {
        mHandler = new Handler();

        GlideApp.with(this)
                .asDrawable()
                .skipMemoryCache(true)
                .signature(new ObjectKey(SharePreferenceUtils.getSplashImageSignKey()))
                .load(SplashApi.image_url)
                .into(mIvBackground);

        new SplashPresenter(this).getImgKey();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mRunnable = new Runnable() {
            @Override
            public void run() {
                startHome();
            }
        };
        mHandler.postDelayed(mRunnable, 3000);
    }

    private void startHome() {
        startActivity(new Intent(this, MainActivity.class));
        /*if (App.get().getUserId() > 0 && App.get().getUserToken() != null) {
        } else {
            startActivity(new Intent(this, LoginActivity.class));
        }*/
        finish();
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacks(mRunnable);
        mHandler = null;
        super.onDestroy();
    }

    @Override
    public void onGetImgKey(long imgKey) {
        long oldKey = SharePreferenceUtils.getSplashImageSignKey();
        if (oldKey != imgKey) {
            GlideApp.with(App.get())
                    .asFile()
                    .signature(new ObjectKey(oldKey))
                    .load(SplashApi.image_url)
                    .into(new SimpleTarget<File>() {
                        @Override
                        public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                            resource.delete();
                        }
                    });
        }

        SharePreferenceUtils.saveSplashImageSignKey(imgKey);
    }
}
